<?php

/**
 * SBaseController class file.
 *
 * @author Spyros Soldatos <spyros@valor.gr>
 * @link http://code.google.com/p/srbac/
 */
/**
 * SBaseController must be extended by all of the applications controllers
 * if the auto srbac should be used.
 * You can import it in your main config file as<br />
 * 'import'=>array(<br />
 * 'application.modules.srbac.controllers.SBaseController',<br />
 * ),
 *
 *
 * @author Spyros Soldatos <spyros@valor.gr>
 * @package srbac.controllers
 * @since 1.0.2
 */


class SBaseController extends Controller {

	//SEO标题
	public $pageTitle = "商家中心";
	//SEO关键字
	public $pageKeyword = '硅胶垫_硅胶管_硅胶套|橡胶密封件_密封条_密封垫_O型密封圈_橡胶垫片|发泡材料-深圳市鑫银特橡胶制品有限公司';
	//SEO描述
	public $pageDesc = '硅胶垫_硅胶管_硅胶套|橡胶密封件_密封条_密封垫_O型密封圈_橡胶垫片|发泡材料-深圳市鑫银特橡胶制品有限公司';
	//SEO模型,默认商家中心
	public $model_name = "company";
	//模块URL前缀
	protected $pre_module_url;
	//活动的方法名称
	public $active_action;
	
	public function init(){
		$modurl = $this->module !== null ? "/".$this->module->id:"";
		$this->pre_module_url = $modurl;
	}
  /**
   * Checks if srbac access is granted for the current user
   * @param String $action . The current action
   * @return boolean true if access is granted else false
   */
  protected function beforeAction($action) {
  	//载入模块分隔符
    $del = '-';
    
    //取得前模块名称
    $mod = $this->module !== null ? $this->module->id . $del : "";
    
    $contrArr = explode("/", $this->id);
    $contrArr[sizeof($contrArr) - 1] = ucfirst($contrArr[sizeof($contrArr) - 1]);
    $controller = implode(".", $contrArr);

    $controller = str_replace("/", ".", $this->id);
    // 生成静态页面 模块+分隔符+控制器（首字母大写）+方法（首字母大写）例： model-ControllerAction
    if(sizeof($contrArr)==1){
      $controller = ucfirst(strtolower($controller));
    }
    $access = $mod . $controller . ucfirst(strtolower($this->action->id));
    //验证访问页面地址是否在总是允许列表里面，是返回有权限
    if (in_array($access, $this->allowedAccess())) {
      return true;
    }
   
   
    //验证SRBAC有无开启，没在开启，返回的权限访问
    if (Yii::app()->params->srbac_debug) {
      return true;
    }
    
  		    // 权限验证,取消原权限验证方法，用自定义方法
	/*	    if (!Yii::app()->user->checkAccess($access) || Yii::app()->user->isGuest) {
		      $this->onUnauthorizedAccess();
		    } else {
		      return true;
		    }*/
	    
	// 自定义权限验证
	if (!$this->checkAccess($access) || Yii::app()->user->isGuest) {
		$this->onUnauthorizedAccess();
	} else {
		return true;
	}
  }

  /**
   * The auth items that access is always  allowed. Configured in srbac module's
   * configuration
   * @return The always allowed auth items
   */
  protected function allowedAccess() {
    return MemGroup::model()->getAllowedAccess();
  }

  protected function onUnauthorizedAccess() {
    /**
     *  Check if the unautorizedacces is a result of the user no longer being logged in.
     *  If so, redirect the user to the login page and after login return the user to the page they tried to open.
     *  If not, show the unautorizedacces message.
     */
    if (Yii::app()->user->isGuest) {
      Yii::app()->user->loginRequired();
    } else {
      $mod = $this->module !== null ? $this->module->id : "";
      $access = $mod . ucfirst($this->id) . ucfirst($this->action->id);
      $error["code"] = "403";
      $error["title"] = Yii::t('srbac', 'You are not authorized for this action');
      $error["message"] = Yii::t('srbac', 'Error while trying to access') . ' ' . $mod . "/" . $this->id . "/" . $this->action->id . ".";
      //You may change the view for unauthorized access
      if (Yii::app()->request->isAjaxRequest) {
      	
        $this->renderPartial(Yii::app()->params->srbac_notAuthorizedView, array("error" => $error));
      } else {
        $this->render(Yii::app()->params->srbac_notAuthorizedView, array("error" => $error));
      }
      return false;
    }
  }

  /**
   * 权限控制，取代原来的权限效验
   */
  protected function checkAccess($item){
  	
  	//获取当前的会员的角色
  	$role = MemGlog::model()->findAllByAttributes(array('userid'=>Yii::app()->user->getId()));
  	foreach($role as $val){
  		//除了角色可以赋给会员外，也可以直接赋值操作给会员，先验证操作权限
  		if($val->itemname==$item){	
  			//子账号操作记录
	  		$this->addLog($item);
	  		return true;
	  	}
  		//查找角色对应的权限
  		$actions = $this->getRoleAction($val->itemname);
  		
  		//先验证操作权限
  		if(!empty($actions)){foreach($actions as $val){
  			if($val->name==$item){
		  		$this->addLog($item);
		  		return true;
		  	}
  		}}
  	}
  	 
  }
   
  /**
   * 获取角色对应的权限
   */
  protected function getRoleAction($roleid){
  	$data = Yii::app()->filecache->get('front_role_action');//获取缓存
  	if(!empty($data)){
  		if(array_key_exists($roleid,$data))
  			return $data[$roleid];
  	}
  	$actions = MemPrivilege::model()->findAllByAttributes(array('parent'=>$roleid));
  	if(!empty($actions)){
  		foreach($actions as $val){
  			$roleaction[] = $val->action;
  		}
  		$data[$roleid] = $roleaction;
  		Yii::app()->filecache->set('front_role_action',$data,3600*24*30);
  		return $roleaction;
  	}else{
  		return;
  	}
  }
  
  /**
   * 操作记录
   */
  public function addLog($itme){
  	$userid = Yii::app()->user->getId();
  	$cmpid = Company::model()->getCmpUserId();
  	if($userid==$cmpid)
  		return;
  	
  	$model = new Log();
  	$model->zm_id = $userid;
  	$model->zlo_name = $itme;
  	$model->zlo_cmp_id = $cmpid;
  	$model->inputtime = time();
  	$model->save();
  	return;
  }
  
}

